import { Component, OnInit, ViewChild, Output, EventEmitter, Inject, forwardRef, ChangeDetectorRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { FileUploader } from '../../../../../lib/ng2-file-upload';
import { ThreeAdvertisingGridComponent } from '../three-advertising-grid/three-advertising-grid.component';
import { SelectImageAddComponent } from './select-image-add/select-image-add.component';
import { AppComponent } from '../../../../app.component';

import { masterService } from '../../../../../lib/master.service';
import { saveVarService } from '../../../../../lib/saveVar.service';
import { path } from '../../../../path.config';

import * as $ from 'jquery';

@Component({
    selector: 'app-three-advertising-add',
    templateUrl: './three-advertising-add.component.html',
    styleUrls: ['./three-advertising-add.component.css'],
    providers: [forwardRef(() => ThreeAdvertisingGridComponent), forwardRef(() => AppComponent), saveVarService]
})

export class ThreeAdvertisingAddComponent implements OnInit {
    @ViewChild('newThreeAd') public newThreeAd: ModalDirective;
    @ViewChild('selectImageAdd') public selectImageGrid: SelectImageAddComponent;

    @Output() threeAdAdd = new EventEmitter<any>();
    // 添加上传的图片
    private addImgItem = path.imagesUpload.apiUrl;

    private addThreeAd = path.advertising.threeAdvertising.addListItem;

    private getImgId = path.imagesUpload.getImgId;
    // 添加列表项传参的对象
    public add: any = {
        type: '',
        url: '',
        imageId: '',
        adName: ''
    }

    // 上传图片获取图片id
    public uploadPic = {};

    constructor(private _masterService: masterService,
        public _saveVar: saveVarService,
        public cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => ThreeAdvertisingGridComponent)) public threeAdGrid: ThreeAdvertisingGridComponent,
        @Inject(forwardRef(() => AppComponent)) private app: AppComponent) {
    }

    ngOnInit() {
    }

    public options: Array<any> = [];

    public uploader: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 打开新建模态框
    public openAddModal() {
        this.selectImageGrid.openAddModal();
    }

    // 新建保存
    public AddListItem() {
        this.add.imageId = this._saveVar.threeAdAddPicId;
        if (!this.add.adName) {
            this.app.toastWarning('请填写名称！');
            return;
        } else if (!this.add.imageId) {
            this.app.toastWarning('请上传图片！');
            return;
        } else if (!this.add.type) {
            this.app.toastWarning('请选择位置！')
            return;
        }

        this._masterService
            .postData(this.addThreeAd, this.add)
            .subscribe((res) => {
                this.newThreeAd.hide();
                if (res.statusCode == 200) {
                    this.app.toastSuccess('新建成功！');
                    this._saveVar.threeAdAddPicId = '';
                    this.threeAdAdd.emit();
                } else {
                    this.app.toastError('错误信息: ' + res.errorMessage);
                }
                // 提交完成后清空新建框
                this.add = {
                    type: '',
                    url: '',
                    imageId: '',
                    adName: ''
                }
                this.uploader.queue = [];
                $('#threeAdUploader').val('');
            })
    }

    // 上传
    uploadFile(thisItem) {
        let that = this;
        if (thisItem == undefined) {
            this.app.toastWarning("请选择图片");
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.uploadPic = {
                    imageName: thisItem.some.name,
                    imageUrl: tempRes.data.url[0],
                    extension: thisItem.some.type.split('/')[thisItem.some.type.split('/').length - 1],
                    imageSize: thisItem.some.size + 'B',
                    resolution: thisItem.resolution
                }
                that._masterService
                    .postData(that.getImgId, that.uploadPic)
                    .subscribe((res) => {
                        if (res.statusCode == 200) {
                            that._saveVar.threeAdAddPicId = res.data;
                            that.app.toastSuccess('上传成功！');
                            that.cdRef.detectChanges();
                        } else {
                            that.app.toastError('错误信息：' + res.errorMessage)
                        }
                    })
            } else {
                // 上传文件后获取服务器返回的数据错误\
                that.app.toastError('错误信息：' + response.errorMessage);
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('错误信息：' + response.errorMessage)
        };

        thisItem.upload(); // 开始上传
    }

    selectedFileOnChanged(event: any) {
        let $this = this;
        let thisItem = $this.uploader.queue[0] = $this.uploader.queue[$this.uploader.queue.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(thisItem.some);
        reader.onload = function (e) {
            thisItem.src = this.result as string;
            var img = new Image();
            img.src = thisItem.src;
            img.onload = function () {
                // 存图片的分辨率
                thisItem.resolution = img.width + '*' + img.height;
            }
        }
        this.cdRef.detectChanges();
    }

    closeModal() {
        this.add = {
            type: '',
            url: '',
            imageId: '',
            adName: ''
        }
        this.uploader.queue = [];
        $('#threeAdUploader').val('');
        this.newThreeAd.hide();
    }
}
